﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LayerEntity.Sistema;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections;
using LayerEntity.Caja;
using LayerLogic;
using DevExpress.XtraReports.UI;
using System2012.Creditos.Reportes;

namespace System2012.Creditos
{
    public partial class frmCtasporCobrar : DevExpress.XtraEditors.XtraForm
    {
        private DataTable dtbCuotas;
        private DataTable  dtbMov;
        private object ID_CREDITO;
        private object ID_CUOTA;
        private object ID_SUCURSAL;
        private string IMPORTE_MORA;
        int indexRow;
        DataTable dtbCreditos = new DataTable();
        private string MONTO_CUOTA;
        private int rowMov;
        private string SALDO_CUOTA;
        /// <summary>
        /// 0: si el los movimientos son por las cuentas por cobraras directamente por estado de cuenta
        /// 1: si los movimientos son por cuotas 
        /// </summary>
        int opMov=0;
        private int rowCuota;
        /// <summary>
        /// Indica si estamos editanado o creando uno Nuevo
        /// 0: Nuevo Documento
        /// 1: Editando y Guardando
        /// </summary>
        int operacion = 0;
        public frmCtasporCobrar()
        {
            InitializeComponent();
            if (!BGWCtasBrar.IsBusy) BGWCtasBrar.RunWorkerAsync();
        }
        private void Amortizar(int op)
        {
           // if (this.dtbCuotas.Rows.Count > 0)
           // {
                if (this.gridView3.RowCount > 0)
                {
                    if (gridView3.SelectedRowsCount > 0)
                    {
                        ArrayList data = new ArrayList();
                        MONTO_CUOTA = dtbCuotas.Rows[rowCuota]["imp_cuota"].ToString();
                        SALDO_CUOTA = dtbCuotas.Rows[rowCuota]["saldo"].ToString();
                        IMPORTE_MORA = dtbCuotas.Rows[rowCuota]["imp_mora"].ToString();
                        ID_CUOTA = dtbCuotas.Rows[rowCuota]["id_cuota"].ToString();
                        ID_CREDITO = dtbCuotas.Rows[rowCuota]["id_credito"].ToString();
                        ID_SUCURSAL = dtbCuotas.Rows[rowCuota]["id_sucursal_credito"].ToString();
                        if (double.Parse(string.Format("{0}",Math.Round(Convert.ToDouble(SALDO_CUOTA),2))) > 0)
                        {
                            data.Add(MONTO_CUOTA);//0
                            data.Add(SALDO_CUOTA);//1
                            data.Add(ID_CUOTA);//2
                            data.Add(ID_CREDITO);//3
                            data.Add(ID_SUCURSAL);//4
                            data.Add(IMPORTE_MORA);//5
                            data.Add(op);//6
                            frmVisorAmortizaCuotas f = new frmVisorAmortizaCuotas(data);
                            f.ShowDialog();
                             if (!BGWCuotas.IsBusy) BGWCuotas.RunWorkerAsync();
                               
                            
                           
                           
                        }
                        else
                        {
                            XtraMessageBox.Show(this, "No exite ningun saldo pendiente \n"
                            + "para realizar esta operacion", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show(this, "No Ha seleccionado ningun Registro", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    XtraMessageBox.Show(this, "No hay ningun registro\n"
                    + "para realizar esta operación", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
           // }
        }
        private void AnularMovCaja()
        {
            
            EMovientoCaja Emov = new EMovientoCaja();
            Emov.Id_sucursal_mov = int.Parse(dtbMov.Rows[0]["ID_SUCURSAL_MOV"].ToString());
            Emov.Serie = dtbMov.Rows[0]["serie"].ToString();
            Emov.Fecha_mov = DateTime.Parse(dtbMov.Rows[0]["fecha"].ToString());
            Emov.Nro_comprobante = dtbMov.Rows[0]["nro_comprobante"].ToString();
            Emov.Id_tranzaccion_mov = dtbMov.Rows[0]["id_tranzaccion_mov"].ToString();
            Emov.Id_documento_mov = int.Parse(dtbMov.Rows[0]["id_documento_mov"].ToString());
            Emov.Id_estado = 7;//anulado
            object[] Msg = System2012.SystemUtils.RecordmanagerCaja.AnulaMovCaja(Emov, this.operacion == 0 ? EnumOperaciones.Insertar : EnumOperaciones.Actualizar);
            if (Msg[0].Equals("0"))
            {
                XtraMessageBox.Show(this, "Movimiento de Caja Anulado", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show(this, Msg[0].ToString());
            }
        }
        private DataSet getMovCaja()
        {
            ESistema obj = new ESistema();
            StringBuilder cadena = new StringBuilder();
            cadena.AppendFormat("where ID_SUCURSAL_MOV={0}", int.Parse(dtbMov.Rows[rowMov]["ID_SUCURSAL_MOV"].ToString()));
            cadena.AppendFormat("and serie='{0}' ", dtbMov.Rows[rowMov]["serie"].ToString());
            cadena.AppendFormat("and fecha='{0}'", dtbMov.Rows[rowMov]["fecha"].ToString());
            cadena.AppendFormat("and nro_comprobante='{0}'", dtbMov.Rows[rowMov]["nro_comprobante"].ToString());
            cadena.AppendFormat("and id_tranzaccion_mov='{0}'", dtbMov.Rows[rowMov]["id_tranzaccion_mov"].ToString());
            cadena.AppendFormat("and id_documento_mov={0}", int.Parse(dtbMov.Rows[rowMov]["id_documento_mov"].ToString()));
            obj.Condicion = cadena.ToString();
            DataTable movCaja = new DataTable("MovCaja");
             movCaja = System2012.SystemUtils.RecordmanagerCaja.getMovPagos(obj); 
            DataSet ds = new DataSet();
            ds.Namespace = "MovCaja";
            movCaja.Namespace = "MovCaja";
            ds.Tables.Add(movCaja);
            return ds;
        }
        private void BGWCtasBrar_DoWork(object sender, DoWorkEventArgs e)
        {
            ESistema obj = new ESistema();
            obj.Condicion = "";
            e.Result = System2012.SystemUtils.RecordManagerCreditos.getCtasporCobrar(obj);
        }

        private void BGWCtasBrar_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            dtbCreditos=(DataTable)e.Result;
            gridControl1.DataSource = dtbCreditos;// e.Result;
         //   if (!BGWCuotas.IsBusy) BGWCuotas.RunWorkerAsync();
        }

        private void BGWCuotas_DoWork(object sender, DoWorkEventArgs e)
        {
            if (indexRow >= 0)
            {
                ESistema obj = new ESistema();
                StringBuilder cadena = new StringBuilder();
                cadena.AppendFormat("where id_credito='{0}'", dtbCreditos.Rows[indexRow]["id_credito"].ToString());
                cadena.AppendFormat("and id_sucursal_credito={0}", dtbCreditos.Rows[indexRow]["id_sucursal_credito"].ToString());
                obj.Condicion = cadena.ToString();
                Console.Write("id_credito : " + dtbCreditos.Rows[indexRow]["id_credito"].ToString());
                e.Result = System2012.SystemUtils.RecordManagerCreditos.getCuotasPorCobrar(obj);
            }
        }

        private void BGWCuotas_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            dtbCuotas = (DataTable)e.Result;
            gridControl2.DataSource = e.Result;
            if (!BGWMovCaja.IsBusy) BGWMovCaja.RunWorkerAsync();
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {  opMov = 0;
            this.indexRow = e.FocusedRowHandle;
          
            if (!BGWCtasBrar.IsBusy)
            {
                if (!BGWCuotas.IsBusy) BGWCuotas.RunWorkerAsync();

            }
        }

        private void BGWMovCaja_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ESistema obj = new ESistema();
                StringBuilder cadena = new StringBuilder();
                if (opMov == 0)
                {
                    if (indexRow >= 0)
                    {
                        cadena.AppendFormat("where id_credito='{0}'", dtbCreditos.Rows[indexRow]["id_credito"].ToString());
                        cadena.AppendFormat("and id_sucursal_credito={0}", dtbCreditos.Rows[indexRow]["id_sucursal_credito"].ToString());
                        obj.Condicion = cadena.ToString();
                        e.Result = System2012.SystemUtils.RecordmanagerCaja.getMovPagos(obj);
                    }
                }
                if (opMov == 1)
                {
                    if (rowCuota >= 0)
                    {
                        if (!BGWCuotas.IsBusy)
                        {
                            if (dtbCuotas.Rows.Count > 0)
                            {
                                cadena.AppendFormat("where id_credito='{0}'", dtbCuotas.Rows[rowCuota]["id_credito"].ToString());
                                cadena.AppendFormat("and id_sucursal_credito={0}", dtbCuotas.Rows[rowCuota]["id_sucursal_credito"].ToString());
                                cadena.AppendFormat("and id_cuota='{0}'", dtbCuotas.Rows[rowCuota]["id_cuota"].ToString());
                                obj.Condicion = cadena.ToString();
                                e.Result = System2012.SystemUtils.RecordmanagerCaja.getMovPagos(obj);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               // throw ex;
            }
            
        }

        private void BGWMovCaja_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            dtbMov = (DataTable)e.Result;
            gridControl3.DataSource = e.Result;
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmAnticipos f = new frmAnticipos();
            f.ShowDialog();
            if (!BGWCtasBrar.IsBusy) BGWCtasBrar.RunWorkerAsync();
        }

        private void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (e.Column.FieldName != "Editar") return;
            GridView gv = sender as GridView;
            string fieldName = gv.GetRowCellValue(e.RowHandle, gv.Columns["documento"]).ToString();
            if (!fieldName.Equals("ANTICIPO"))
            {
                e.RepositoryItem = repositoryItemHyperLinkEdit1;
            }
            /*switch (fieldName)
            {
                case "ANTICIPO":
             
                    break;               
            }*/
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
           
        }

        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {
            if (e.Clicks == 2)
            {
                if (gridView1.FocusedColumn == this.gridView1.Columns["Editar"])
                {
                    if (dtbCreditos.Rows[indexRow]["documento"].Equals("ANTICIPO"))
                    {
                        frmEditarAnticipo f = new frmEditarAnticipo(dtbCreditos, indexRow);
                        f.ShowDialog();
                        if (!BGWCtasBrar.IsBusy) BGWCtasBrar.RunWorkerAsync();
                    }
                    else
                    {
                         // XtraMessageBox.Show(this, "El registro no es un anticipo", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void gridView1_Click(object sender, EventArgs e)
        {
           
        }

        private void gridView3_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        { 
            opMov = 1;
           rowCuota = e.FocusedRowHandle;
          
           if (!BGWMovCaja.IsBusy) BGWMovCaja.RunWorkerAsync();
        }

        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Amortizar(1);
            
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void barButtonItem12_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show(this, "Está a punto de anular el Movimiento de caja\n" +
                                    "Confirmación Requerida ?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                AnularMovCaja();
            }
            
           

        }
        private void gridView4_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            rowMov = e.FocusedRowHandle;
            if (rowMov >= 0)
            {
                
            }
        }

        private void gridView4_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                GridView view = sender as GridView;
                if (view.GetRowCellValue(e.RowHandle, view.Columns["estado_mov"]).ToString() == "ANULADO")
                {
                    e.Appearance.BackColor = Color.Red;
                    e.Appearance.ForeColor = Color.Snow;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                }
            }
        }

        private void gridView3_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                GridView view = sender as GridView;
                if (view.GetRowCellValue(e.RowHandle, view.Columns["estado"]).ToString() == "ANULADO")
                {
                    e.Appearance.BackColor = Color.Red;
                    e.Appearance.ForeColor = Color.Snow;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                }
                else
                {
                    if (view.GetRowCellValue(e.RowHandle, view.Columns["estado"]).ToString() == "MORA")
                    {
                        e.Appearance.BackColor = Color.OrangeRed;
                        e.Appearance.ForeColor = Color.Snow;
                        
                    }
                    else
                    {
                        if (view.GetRowCellValue(e.RowHandle, view.Columns["estado"]).ToString() == "CANCELADA")
                        {
                            e.Appearance.BackColor = Color.Yellow;
                            //e.Appearance.ForeColor = Color.Snow;
                            
                        }
                        else
                        {
                            if (view.GetRowCellValue(e.RowHandle, view.Columns["estado"]).ToString() == "VENCIADA")
                            {
                                e.Appearance.BackColor = Color.DarkOrange;
                                e.Appearance.ForeColor = Color.Snow;
                               
                            }
                            
                        }
                    }
                }
            }
        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            Reportes.rptMovimientoCaja f = new System2012.Creditos.Reportes.rptMovimientoCaja(rowMov,1,dtbMov);
            f.ShowDialog();
            /*getMovCaja().WriteXml(@"D:\Templates\ConfigXML\xmlMovCaja.xml");
            XtraReport report = new XtraReport();
            ESistema obj = new ESistema();
            obj.Condicion = "";
            //DataTable facturacion = System2012.SystemUtils.RecordManagerFacturacion.GetCabeceraFacturacion(obj);
            report.DataSource = getMovCaja();// facturacion;
            report.LoadLayout(@"D:\Templates\Plantillas\Caja\repMovcaja.repx");
            report.ShowPreview();
            */
        }

        private void barButtonItem14_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            getMovCaja().WriteXml(@"D:\Templates\ConfigXML\xmlMovCaja.xml");
           XtraReport report = new XtraReport();
           ESistema obj = new ESistema();
           obj.Condicion = "";
           //DataTable facturacion = System2012.SystemUtils.RecordManagerFacturacion.GetCabeceraFacturacion(obj);
           report.DataSource = getMovCaja();// facturacion;
           report.LoadLayout(@"D:\Templates\Plantillas\Caja\repMovcaja.repx");
           report.ShowPreview();
           
        }

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
         /*   frmTemplateReport r = new frmTemplateReport(indexRow, 2, dtbCreditos);
            r.ShowDialog();*/
            
            Reportes.rptMovimientoCaja f = new System2012.Creditos.Reportes.rptMovimientoCaja(indexRow, 2, dtbCreditos);
            f.ShowDialog();
             
        }

        private void barButtonItem11_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Reportes.rptMovimientoCaja f = new System2012.Creditos.Reportes.rptMovimientoCaja(indexRow, 3, dtbCreditos);
            f.ShowDialog();
        }

        private void frmCtasporCobrar_Load(object sender, EventArgs e)
        {

        }
    }
}